<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Services\AdminManager;
use App\User;
use App\VipInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class VipController extends Controller
{
    public function getUserVipList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $userId = $request->input('user_id',0);

        $vipInfos = VipInfo::whereUserId($userId)->get();
        if(count($vipInfos) > 0){
            foreach ($vipInfos as $vipInfo) {
                $vipInfo->type_name = VipInfo::getVipTypeName($vipInfo->type);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipInfos]);
    }

    public function setUserVip(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $userId  = $request->input('user_id',0);
        $vipArr = $request->input('vip_arr');

        $user = User::whereId($userId)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '用户不存在']);

        if(is_array($vipArr) && count($vipArr) > 0){
            $typeArr = [];
            foreach ($vipArr as $vip) {
                $type    = !empty($vip['type']) ? $vip['type'] : '';
                $price   = !empty($vip['price']) ? $vip['price'] : 0;
                $num     = !empty($vip['num']) ? $vip['num'] : 0;
                $endTime = !empty($vip['end_time']) ? $vip['end_time'] : '';

                if(in_array($type,['num','time'])){
                    $vipInfo = VipInfo::whereUserId($user->id)->whereType($type)->first();
                    if(!$vipInfo)
                        $vipInfo = new VipInfo();

                    $vipInfo->user_id  = $user->id;
                    $vipInfo->type     = $type;
                    $vipInfo->price    = $price;
                    $vipInfo->num      = $num;
                    if($endTime)
                        $vipInfo->end_time = $endTime;
                    $vipInfo->save();

                    array_push($typeArr,$type);
                }
            }

            VipInfo::whereUserId($user->id)->whereNotIn('type',$typeArr)->delete();
        }else{
            $vipInfoList = VipInfo::whereUserId($user->id)->get();
            if(count($vipInfoList) > 0){
                foreach ($vipInfoList as $vipInfo) {
                    $vipInfo->delete();
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }


}
